﻿using LiteDB;
using System;
using System.Collections.Generic;

namespace NDK.Module.Project.信维AFMT
{
    public interface ILiteData
    {
        int ID { get; set; }
    }

    public enum LiteDBOperate
    {
        Add,
        Delete,
        Update
    }

    public class LiteDataBase
    {
        public string MyDataBase { get; set; } = "AlexData.db";
        public bool Operate (ILiteData data, string form, LiteDBOperate operate)
        {
            try
            {
                using(var db = new LiteDatabase(MyDataBase))
                {
                    // 获取集合（相当于表）
                    var collection = db.GetCollection<ILiteData>(form);
                    switch(operate)
                    {
                        case LiteDBOperate.Add:
                            collection.Insert(data);
                            break;
                        case LiteDBOperate.Delete:
                            collection.Delete(data.ID);
                            break;
                        case LiteDBOperate.Update:
                            collection.Update(data);
                            break;
                    }
                    return true;
                }
            }
            catch(Exception)
            {
                return false;
            }
        }

        public IEnumerable<T> Find<T> (string form)
        {
            try
            {
                using(var db = new LiteDatabase(MyDataBase))
                {
                    // 获取集合（相当于表）
                    var collection = db.GetCollection<T>(form);
                    return collection.FindAll();
                }
            }
            catch(Exception)
            {
                return null;
            }
        }
    }
}
